import type {ActionType, ProColumnType} from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProTable,
} from '@ant-design/pro-components';
import {Button, message, Popconfirm, Modal} from 'antd';
import React, {useRef, useState} from 'react';
import type {TableListItem, TableListPagination} from './data';
import {getApplyPage, batchDelApply} from './service';
import './index.less'

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [selectedRowsState, setSelectedRows] = useState<TableListItem[]>([]);
  const columns: ProColumnType<any>[] = [
    {
      title: '序号',
      dataIndex: '#',
      key: '#',
      width: 100,
      fixed: 'left',
      hideInSearch: true,
      hideInForm: true,
      render(dom, entity, index) {
        return index + 1;
      },
      editable: false,
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      fieldProps: {
        placeholder: '请输入项目名称'
      },

      key: 'projectName',
      // width: '20%',
    },
    {
      title: '类型',
      dataIndex: 'type',
      fieldProps: {
        placeholder: '请选择类型'
      },
      valueType: 'select',
      valueEnum: {
        inquiry: {text: '询价'},
        sample_apply: {text: '样品申请'},
      }
    },
    {
      title: '关联产品',
      dataIndex: 'productName',
      hideInSearch: true,
      render(dom, entity) {
        try {
          const name = Object.values(JSON.parse(entity.productName))?.[0]
          return <>{name || '-'}</>
        } catch (e) {
        }
        return '-'
      }
    },
    {
      title: '公司名称',
      dataIndex: 'companyName',
      fieldProps: {
        placeholder: '请输入公司名称'
      },
    },
    {
      title: '联系人',
      dataIndex: 'contacts',
      fieldProps: {
        placeholder: '请输入联系人'
      },
      hideInSearch: true,
      key: 'contacts',
      // width: '20%',
    },
    {
      title: '手机号',
      dataIndex: 'phoneNumber',
      fieldProps: {
        placeholder: '请输入手机号'
      },
      hideInSearch: true,
      key: 'phoneNumber',
      // width: '20%',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      fieldProps: {
        placeholder: '请输入邮箱'
      },
      hideInSearch: true,
      key: 'email',
      // width: '20%',
    },
    {
      title: '需求描述',
      dataIndex: 'remarks',
      fieldProps: {
        placeholder: '请输入需求描述'
      },
      valueType: 'textarea',
      hideInSearch: true,
      key: 'remarks',
      // width: '20%',
    },

    {
      title: '创建时间',
      dataIndex: 'gmtCreate',
      key: 'gmtCreate',
      hideInSearch: true,
      valueType: 'dateTime',
      hideInForm: true,
    },
    {
      title: '更新时间',
      dataIndex: 'gmtModified',
      key: 'gmtModified',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 120,
      valueType: 'option',
      render: (_, record: any) => {
        return [
          <Popconfirm
            key="del"
            title="删除样品申请"
            description={<>
              <p>确认删除 <b>{record?.name}</b> 样品申请?</p>
            </>}
            onConfirm={async () => {
              const hide = message.loading('正在删除');

              try {
                const res = await batchDelApply({
                  idList: [record?.id]
                })
                hide();
                if (res.code === 0) {
                  message.success('删除成功');
                  actionRef.current?.reload()
                  return true
                } else {
                  hide();
                  message.error('删除失败请重试！');
                  return false;
                }
              } catch (e) {
                hide();
                message.error('删除失败请重试！');
                return false;
              }
            }}
            okText="是"
            cancelText="否"
          >
            <a>删除</a>
          </Popconfirm>
          ,
        ];
      },
    },
  ];

  return (
    <PageContainer className='Apply_wrap'>
      <ProTable<TableListItem, TableListPagination>
        headerTitle="申请管理"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        scroll={{x: 'max-content'}}
        request={async ({current, pageSize, ...other}) => {
          // @ts-ignore
          const res = await getApplyPage({
            page: current,
            size: pageSize,
            ...other
          })

          return {
            total: res?.data?.total_records,
            data: res?.data?.current_data
          }
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState?.length}
              </a>{' '}
              项 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              Modal.confirm({
                title: `确认删除 ${selectedRowsState?.length} 条数据?`,
                content: `请谨慎操作，删除后不可恢复`,
                async onOk() {
                  const hide = message.loading('正在删除');

                  try {
                    const res = await batchDelApply({
                      idList: selectedRowsState?.map((item: any) => item.id)
                    })
                    hide();
                    if (res.code === 0) {
                      message.success('删除成功');
                      setSelectedRows([]);
                      actionRef.current?.reload()
                      return true
                    } else {
                      hide();
                      message.error('删除失败请重试！');
                      return false;
                    }
                  } catch (e) {
                    hide();
                    message.error('删除失败请重试！');
                    return false;
                  }

                }
              })
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}
    </PageContainer>
  );
};

export default TableList;
